

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WHY
 * Date: 2023-03-23
 * Time: 14:32
 */
//自己实现阻塞队列
    class  MyBlockingQueue{
     volatile    private int[] items=new int[1000];
    volatile     private int head=0;
     volatile    private int tail=0;
      volatile   private int size=0;
        //入队列
 synchronized    public void put(int elem) throws InterruptedException {
        while(size==items.length){
            //return;
            this.wait();
        }
        items[tail]=elem;
        tail++;
        if(tail==items.length){
            tail=0;
        }
        size++;
        this.notify();
    }
  synchronized   public Integer take() throws InterruptedException {
        while(size==0){
          //  return null;
            this.wait();
        }
        int value=items[head];
        head++;
        if(head==items.length){
            head=0;
        }
        size--;
        this.notify();
        return value;
    }

}


public class ThreadDemo2 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        //消费者
        Thread t1 = new Thread(()->{
            while (true) {
                int value = 0;
                try {
                    value = queue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("消费" + value);
            }
        });
        t1.start();
        Thread t2=new Thread(()->{
            int value=0;
            while(true){
                try {
                    queue.put(value);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产"+value);
                value++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        t2.start();
        System.out.println("hello");

    }

    }

